<script setup lang="ts">
import AppTable from "@/components/app/AppTable.vue";
import DictOptionView from "@/views/system/dict/dictOptionView.vue";
import {ref} from "vue";
import {alertSuccess, confirm} from "@/utils/alert.ts";
import {deleteDict, createDict, updateDict} from "@/api/system";
import type {IDictParams} from "@/types";

defineOptions({
  // eslint-disable-next-line vue/multi-word-component-names
  name: "Dict"
})
const tableRef = ref()
const dict = ref<any | null>()
const formDialogTableVisible = ref<boolean>(false)
const formDialogTableVisibleType = ref<'add' | 'edit'>('add')
const viewDialogTableVisible = ref<boolean>(false)
const selectedId = ref<any | null>()
const params = ref<IDictParams>({} as IDictParams)


const handleSave = () => {
  if (formDialogTableVisibleType.value === 'add') {
    createDict(params.value).then(() => {
      alertSuccess('保存成功')
      tableRef.value.queryData();
      formDialogTableVisible.value = false
    })
  }
  if (formDialogTableVisibleType.value === 'edit') {
    updateDict(selectedId.value ? selectedId?.value : 0, params.value).then(() => {
      alertSuccess('保存成功')
      tableRef.value.queryData();
      formDialogTableVisible.value = false
    })
  }
}


const handleDelete = (id: string) => {
  confirm('确定要删除吗？', async () => {
    await deleteDict(id)
    tableRef.value.queryData();
    alertSuccess('删除成功')
  })
}


const handleBtnClick = (key: string, data: any[] | null) => {
  console.log(key, data)
  if (key === 'delete') {
    if (data) {
      handleDelete(data[0]?.key)
    }
  }
  if (key === 'add') {
    formDialogTableVisibleType.value = 'add'
    openFormDialogView()
  }
  if (key === 'edit') {
    formDialogTableVisibleType.value = 'edit'
    if (data) {

      openFormDialogView(data[0])
    }
  }
}

const openDictOptionView = (data: any) => {
  dict.value = data
  viewDialogTableVisible.value = true
}


const openFormDialogView = (data: any = undefined) => {
  if (formDialogTableVisibleType.value === 'add') {
    params.value = {
      name: '',
      code: '',
      type: 'list',
      status: '0',
      children: [
        {
          label: '示例',
          value: '0',
          status: '0',
          sort: 0
        }
      ]
    }
  }
  if (formDialogTableVisibleType.value === 'edit') {
    params.value = {
      name: data.name,
      code: data.code,
      type: data.type,
      status: data.status,
      children: []
    }
    selectedId.value = data.id
  }
  formDialogTableVisible.value = true
}


const addDictOption = () => {
  const len = params.value.children.length
  params.value.children.push({
    label: '示例' + len,
    value: '' + len,
    status: '0',
    sort: len
  })
}
</script>

<template>
  <div>
    <AppTable
      title="字典管理"
      ref="tableRef"
      :search-info="[
  {
    label: '字典名称',
    key: 'name',
    value: ''
  },  {
    label: '字典编码',
    key: 'code',
    value: ''
  },  {
    label: '类型',
    key: 'type',
    value: '',
    type: 'select',
    options: [{
      value: 'list',
      label: 'list'
    }, {
      value: 'tree',
      label: 'tree'
    }]
  },  {
    label: '状态',
    key: 'status',
    value: '',
    type: 'select',
    options: [{
  value: '0',
  label: '启用'
}, {
  value: '1',
  label: '停用'
}]
  },
]"
      :btn-show="{add: true, edit: true, delete: false, export:false, import:false}"
      :pageable="true"
      api-method="get"
      api-path="/api/sys/dict/queryPage"
      @handle-btn-click="handleBtnClick"
      @multiple-selection="data => {if(data&&data.length>0){selectedId = data[0]['id']}}">
      <template v-slot:actionBar>
      </template>
      <template v-slot:tableColumn>
        <el-table-column prop="id" label="编号" width="70" align="left"/>
        <el-table-column prop="name" label="字典名称" align="left"/>
        <el-table-column prop="code" label="字典编码" align="left"/>
        <el-table-column prop="type" label="类型" width="200" align="center"/>
        <el-table-column label="状态" width="200" align="center">
          <template #default="scope">
            <el-button link v-if="scope.row.status === '0'" type="success">启用</el-button>
            <el-button link v-else-if="scope.row.status === '1'" type="danger">停用</el-button>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button link type="primary" size="small" icon="Edit"
                       @click="formDialogTableVisibleType = 'edit';openFormDialogView(scope.row)">
              编辑
            </el-button>
            <el-button link type="primary" size="small" @click="openDictOptionView(scope.row)"
                       icon="View">
              查看
            </el-button>
            <el-button link type="danger" size="small" icon="Delete"
                       @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </AppTable>

    <el-dialog v-model="viewDialogTableVisible" title="数据字典">
      <DictOptionView :dict="dict"/>
    </el-dialog>

    <el-dialog v-model="formDialogTableVisible" title="数据字典"
               width="700px"
               :close-on-click-modal="false">
      <el-form ref="form" :model="params" label-width="80px">
        <el-form-item label="字典名称">
          <el-input v-model="params.name" placeholder="请输入字典名称"/>
        </el-form-item>
        <el-form-item label="字典编码">
          <el-input v-model="params.code" placeholder="请输入字典编码"/>
        </el-form-item>
        <el-form-item label="字典类型">
          <el-select
            :disabled="formDialogTableVisibleType==='edit'"
            v-model="params.type" placeholder="请选择字典类型">
            <el-option label="list" value="list"/>
            <el-option label="tree" value="tree"/>
          </el-select>
        </el-form-item>
        <el-form-item label="字典状态">
          <el-select v-model="params.status" placeholder="请选择字典状态">
            <el-option label="启用" value="0"/>
            <el-option label="停用" value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="formDialogTableVisibleType==='add'">
        <div style="margin: 15px auto;text-align: right;">
          <el-button type="warning" size="small" @click="addDictOption">添加字典项</el-button>
        </div>
        <div>
          <el-table
            :data="params.children"
            stripe
            border
            style="width: 100%">
            <el-table-column label="字典名称" align="left">
              <template #default="scope">
                <el-input v-model="scope.row.label"/>
              </template>
            </el-table-column>
            <el-table-column label="字典编码" align="left">
              <template #default="scope">
                <el-input v-model="scope.row.value"/>
              </template>
            </el-table-column>
            <el-table-column label="排序" width="100" align="center">
              <template #default="scope">
                <el-input type="number" v-model="scope.row.sort"/>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
              <template #default="scope">
                <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"/>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button link type="danger" size="small" icon="Delete"
                           @click="()=>{params.children.splice(scope.$index, 1)}">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <template #footer>
        <el-button @click="formDialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>
